package com.xoa.controller.hr;

import com.xoa.dao.common.SysCodeMapper;
import com.xoa.dao.hr.HrStaffEntryEducationMapper;
import com.xoa.dao.hr.HrStaffEntryExperienceMapper;
import com.xoa.dao.sms.SmsMapper;


import com.xoa.model.common.SysCode;
import com.xoa.model.hr.HrStaffEntryEducation;
import com.xoa.model.hr.HrStaffEntryExperience;
import com.xoa.model.hr.HrStaffEntryWithBLOBs;
import com.xoa.model.users.Users;
import com.xoa.service.hr.HrStaffEntryService;
import com.xoa.service.users.UsersService;
import com.xoa.util.CookiesUtil;
import com.xoa.util.ToJson;
import com.xoa.util.common.session.SessionUtils;
import org.apache.commons.httpclient.DefaultHttpMethodRetryHandler;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.NameValuePair;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.httpclient.params.HttpMethodParams;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.net.URLEncoder;
import java.util.List;
import java.util.Random;


@Controller
@RequestMapping("/hr/staffEntry")
public class HrStaffEntryController {
    @Resource
    SmsMapper smsMapper;
    @Autowired
    private HrStaffEntryService hrStaffEntryService;
    @Autowired
    private SysCodeMapper sysCodeMapper;
    @Resource
    private HrStaffEntryEducationMapper hrStaffEntryEducationMapper;
    @Resource
    private HrStaffEntryExperienceMapper hrStaffEntryExperienceMapper;
    @Autowired
    private UsersService usersService;



     @RequestMapping("/auditUpdate")
     @ResponseBody
     public ToJson apply(HttpServletRequest request, String auditState, Integer id, String msg) {
     return hrStaffEntryService.updateStateById(request,auditState,id,msg) ;
     }


     /**
     * 添加入职资料(注册)
     */
    @RequestMapping("/insert")
    @ResponseBody
    public ToJson insert(@RequestBody HrStaffEntryWithBLOBs hrStaffEntrys, HttpServletRequest request){
        return hrStaffEntryService.insert(hrStaffEntrys,request);

    }

    /**
     * 普通短信
     * @throws Exception
     */
    @RequestMapping("/sendVerificationCode")
    @ResponseBody
    private String sendVerificationCode(String staffPhone) throws Exception {

        //随机生成六位数验证码
        Random random = new Random();
        String result="";
        for (int i=0;i<6;i++)
        {
            result += random.nextInt(10);
        }


        //发送验证码
        HttpClient httpClient = new HttpClient();
        PostMethod postMethod = new PostMethod("http://api.1cloudsp.com/api/v2/single_send");
        postMethod.getParams().setContentCharset("UTF-8");
        postMethod.getParams().setParameter(HttpMethodParams.RETRY_HANDLER,new DefaultHttpMethodRetryHandler());

        String accesskey = "JwZ8PPCmaNwmwxCU"; //用户开发key
        String accessSecret = "QKEWlahM1NTKWfl8cwYAKL6PCDrkwNwK"; //用户开发秘钥

        NameValuePair[] data = {
                new NameValuePair("accesskey", accesskey),
                new NameValuePair("secret", accessSecret),
                new NameValuePair("sign", "135279"),
                new NameValuePair("templateId", "158623"),
                new NameValuePair("mobile", staffPhone),
                new NameValuePair("content", URLEncoder.encode(result, "utf-8"))//（示例模板：{1}您好，您的订单于{2}已通过{3}发货，运单号{4}）
        };
        postMethod.setRequestBody(data);
        postMethod.setRequestHeader("Connection", "close");

        int statusCode = httpClient.executeMethod(postMethod);
        System.out.println("statusCode: " + statusCode + ", body: "
                + postMethod.getResponseBodyAsString());


//        HttpSession session = request.getSession();
//        session.setAttribute(staffPhone,result);
//        session.setMaxInactiveInterval(30 * 60);

        return result;

    }
    /*public static void main(String[] args) throws Exception {
        HrStaffEntryController t = new HrStaffEntryController();
        //普通短信
        t.sendVerificationCode("15701327501");

    }*/

    /**
     * 查询品类
     * @param request
     * @return
     */
    @RequestMapping("/selectCategory")
    @ResponseBody
    public ToJson<Integer> selectByCurrency(HttpServletRequest request){
        ToJson json =new ToJson<Integer>(1,"err");
        try {
            List<SysCode> sysCodes=sysCodeMapper.getSysCode("CATEGORY");
            if(sysCodes!=null){
                json.setObj(sysCodes);
                json.setFlag(0);
                json.setMsg("true");
            }
        }catch(Exception e){
            e.printStackTrace();
        }
        return json;
    }

    /**
     * 查询品类
     * @param
     * @return
     */
    @RequestMapping("/selectBrand")
    @ResponseBody
    public ToJson<Integer> selectBrand(String codeNo){
        ToJson json =new ToJson<Integer>(1,"err");
        try {
            List<SysCode> sysCodes=sysCodeMapper.getSysCode(codeNo);
            if(sysCodes!=null){
                json.setObj(sysCodes);
                json.setFlag(0);
                json.setMsg("true");
            }
        }catch(Exception e){
            e.printStackTrace();
        }
        return json;
    }

    /**
     * 查询岗位
     * @param request
     * @return
     */
    @RequestMapping("/selectWordJob")
    @ResponseBody
    public ToJson<Integer> selectWordJob(HttpServletRequest request){
        ToJson json =new ToJson<Integer>(1,"err");
        try {
            List<SysCode> sysCodes=sysCodeMapper.getSysCode("jd_wordjob");
            if(sysCodes!=null){
                json.setObj(sysCodes);
                json.setFlag(0);
                json.setMsg("true");
            }
        }catch(Exception e){
            e.printStackTrace();
        }
        return json;
    }
    /**
     * 查询岗位
     * @param request
     * @return
     */
    @RequestMapping("/selectEntryById")
    @ResponseBody
    public ToJson<Integer> selectEntryById(HttpServletRequest request, Integer id){
        ToJson json =new ToJson<Integer>(1,"err");
        try {
            HrStaffEntryWithBLOBs hrStaffEntry=hrStaffEntryService.selectEntryById(id,request);
            Cookie redisSessionId = CookiesUtil.getCookieByName(request,"redisSessionId");
            Users user = SessionUtils.getSessionInfo(request.getSession(),Users.class,new Users(),redisSessionId);
            //消除事务提醒
            smsMapper.setReadByUrl(user.getUserId(),"/personManagement/newIntroduction?id="+id);
            List<HrStaffEntryEducation> hrStaffEntryEducation = hrStaffEntryEducationMapper.selectByDid(hrStaffEntry.getId());
           // hrStaffEntry.setHrStaffEntryEducationList(hrStaffEntryEducation);
            List<HrStaffEntryExperience> hrStaffEntryExperience = hrStaffEntryExperienceMapper.selectByDid(hrStaffEntry.getId());
            if(hrStaffEntry!=null){
                hrStaffEntry.setUserPriv(user.getUserPriv()+"");
                hrStaffEntry.setUserId(user.getUserId());
                hrStaffEntry.setHrStaffEntryEducationList(hrStaffEntryEducation);
                hrStaffEntry.setHrStaffEntryExperienceList(hrStaffEntryExperience);
                json.setObject(hrStaffEntry);
                json.setFlag(0);
                json.setMsg("true");
            }
        }catch(Exception e){
            e.printStackTrace();
        }
        return json;
    }

    // 导入品类和品牌
    @ResponseBody
    @RequestMapping("/importBrandAndCategory")
    public ToJson importBrandAndCategory(MultipartFile file, HttpServletRequest request, HttpServletResponse response){
        return hrStaffEntryService.importBrandAndCategory(file, request, response);
    }

    @ResponseBody
    @RequestMapping("/exportBrandAndCategory")
    public void exportBrandAndCategory(HttpServletRequest request, HttpServletResponse response){
        hrStaffEntryService.exportBrandAndCategory(request, response);
    }

    @ResponseBody
    @RequestMapping("/update")
    public ToJson update(@RequestBody HrStaffEntryWithBLOBs hrStaffEntrys, HttpServletRequest request){
        return hrStaffEntryService.update(hrStaffEntrys,request);
    }

    @ResponseBody
    @RequestMapping("/deleteSysCode")
    public void deleteSysCode(Integer minId,Integer maxId){
        sysCodeMapper.deleteMinToMax(minId,maxId);
    }

    @ResponseBody
    @RequestMapping("/setDefulatPw")
    public String setDefualtPw(HttpServletRequest request){
        List<Users> nullPwUsers = usersService.getNullPwUsers(null);
        for (int i = 0; i < nullPwUsers.size(); i++) {
            Users users = nullPwUsers.get(i);
            users.setPassword("");
            usersService.editPwd(request,users,"abc123");
        }
        return "ok";
    }

}
